package schoolsource.command;

import java.io.IOException;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.logging.Level;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import schoolsource.config.ConfigurationItems;
import schoolsource.gui.FormFields;
import schoolsource.gui.FormParser;
import schoolsource.model.AttachmentContainer;
import schoolsource.model.AttendanceContainer;
import schoolsource.model.ClassContainer;
import schoolsource.model.ContactContainer;
import schoolsource.model.GradeContainer;
import schoolsource.model.HomeworkContainer;
import schoolsource.model.Item;
import schoolsource.model.MessageContainer;
import schoolsource.model.PairedUserContainer;
import schoolsource.model.PasswordItem;
import schoolsource.model.StringItem;
import schoolsource.model.SubmissionContainer;
import schoolsource.model.UserContainer;
import schoolsource.security.SecurityAuthorizer;
import schoolsource.security.SecurityToken;
import schoolsource.sql.SchoolDBSQL;
import schoolsource.util.SchoolLogger;
import schoolsource.util.Types;

/**
 *
 * @author Steven Steele
 * Copyright 2003
 *
 * Manages all teacher accesses.
 */
public class TeacherAccessCMD extends HttpServlet {

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     **/
    public void doPost(HttpServletRequest input, HttpServletResponse response)
        throws ServletException, IOException {

                                response.setContentType("text/html; charset=ISO-8859-2");
        //SchoolLogger.logger.log(Level.INFO, "TeacherAccessCMD start");

        SecurityToken st = null;

        // Set up request dispatcher to display the next page.
        RequestDispatcher disp;
        ServletContext sc = getServletContext();

        Enumeration e = input.getParameterNames();
        String s;
        //SchoolLogger.logger.log(Level.INFO, "List parameter values");
        while (e.hasMoreElements()) {
            s = (String) e.nextElement();
            //SchoolLogger.logger.log(
                //Level.INFO,
                //s + ":  " + input.getParameter(s));
        }

        String token = null;

        String link = input.getParameter(FormFields.BUTTONCLICKED);
        if (link == null) {
            link = input.getParameter(FormFields.LINKCLICKED);
            //SchoolLogger.logger.log(Level.INFO, "link clicked: " + link);
        }
        String current = input.getParameter(FormFields.CURRENT);
        String param = input.getParameter(FormFields.PARAMETER);
        String userType = (String) input.getParameter(FormFields.USRTYPE);
        String schoolName = (String) input.getParameter(FormFields.SCHOOLNAME);
        input.setAttribute(FormFields.SCHOOLNAME, schoolName);
        input.setAttribute(FormFields.USRTYPE, userType);

        // Validate token. If not valid, send back the login page with
        // the appropriate message
        if ((token = input.getParameter(FormFields.TOKEN)) != null) {
            if (FormFields.LOGOUT.equals(link)) {
                //SchoolLogger.logger.log(Level.INFO, "Logged out 1");
                SecurityAuthorizer.removeToken(token);
                // TODO: change message to a static constant.
                input.setAttribute("message", "User logged out.");
                disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
            }
            else if (
                (st = SecurityAuthorizer.validateToken(token, 'T')) != null) {
                // put the Token in the request so the jsp can retrieve it
                input.setAttribute(FormFields.SESSION, st);

                //SchoolLogger.logger.log(Level.INFO, "valid token");

                // Determine which page the user was on (by the 'CURRENT' parameter),
                // determine what the user did (BUTTONCLICKED), and get the parameter
                // (PARAMETER)
                if (current.equals(FormFields.TEACHERCLASSINFO)) {
                    //SchoolLogger.logger.log(
                        //Level.INFO,
                        //"current == TEACHERCLASSINFO");
                    // If the user clicked refresh, then reload all info and redisplay the
                    // page the user was on
                    // This should be improved to refresh all pages - as it is now, anything
                    // in the view frame is lost.
                    if (("Refresh".equals(link))) {
                        int classnum =
                            (new Integer((String) st
                                .getValue(FormFields.CLASSNUM)))
                                .intValue();
                        ClassContainer classC[] =
                            (ClassContainer[]) st.getValue("classContainer");
                        UserContainer teacherContainer =
                            (UserContainer) st.getValue("teacherContainer");
                        if (classnum == -2)
                            getTodaysPage(teacherContainer, st);
                        else if (classnum != -1)
                            getClassPage(
                                classC[classnum],
                                teacherContainer,
                                st);
                        disp = sc.getRequestDispatcher("/jsp/TeacherClassInfo.jsp");
                    }
                    // If the user clicked a class, load and display informaiton for the new
                    // class
                    else if (FormFields.TEACHERCLASSINFO.equals(link)) {
                        int classnum = new Integer(param).intValue();
                        ClassContainer classC[] =
                            (ClassContainer[]) st.getValue("classContainer");
                        st.putValue(FormFields.CLASSNUM, param);
                        UserContainer teacherContainer =
                            (UserContainer) st.getValue("teacherContainer");
                        if (classnum == -2)
                            getTodaysPage(teacherContainer, st);
                        else
                            getClassPage(classC[classnum], teacherContainer, st);
                        disp = sc.getRequestDispatcher("/jsp/TeacherClassInfo.jsp");
                    }
                    // Unrecognized link - load the main page.
                    else {
                        disp = sc.getRequestDispatcher("/jsp/TeacherClassInfo.jsp");
                    }
                }
                // If the user elected to work with a mail or homework
                else if (current.equals(FormFields.SUBFRAME)) {
                    //SchoolLogger.logger.log(Level.INFO, "current == SUBFRAME");
                    st.putValue(FormFields.CLASSNUM, input.getParameter(FormFields.CLASSNUM));
                    //If the user clicked an email, then display it
                    if (FormFields.MAILLINK.equals(link)) {

                        st.putValue(FormFields.MAILNUM, param);
                        int mailnum =
                            (new Integer((String) st.getValue(FormFields.MAILNUM))).intValue();

                        if (mailnum != -1) {
                            ContactContainer cc =
                                ((ContactContainer[]) st.getValue("communicationContainer"))[mailnum];
                            cc.getHidden().setValue("TRUE");
                            SchoolDBSQL.getSchoolDBSQL(schoolName).save(cc);
                        }

//                      int loc =
//                          new Integer(cc.getClassAssignedID().toString()).intValue();

                        int classnum = new Integer((String) st.getValue(FormFields.CLASSNUM)).intValue();

                    	ClassContainer classC[] = (ClassContainer[]) st.getValue("classContainer");
                        if (classnum != -2) {
                       	    UserContainer sapl[][] =
	                         	SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).
	                            loadRecipientList(classC[classnum].getClassAssignedID());
                            st.putValue("studentAndParentList", sapl);
                        }

                        disp = sc.getRequestDispatcher("/jsp/TeacherMailForm.jsp");
                    }
                    // If the user elected to delete mail, then delete it.
                    else if (FormFields.DELMAIL.equals(link)) {
                        int mailnum =
                            (new Integer((String) st.getValue(FormFields.MAILNUM))).intValue();
                        ContactContainer cc =
                            ((ContactContainer[]) st.getValue("communicationContainer"))[mailnum];
                        SchoolDBSQL.getSchoolDBSQL(
                            (String) st.getValue(FormFields.SCHOOLNAME)).moveContactToDeleted(cc);
                        st.putValue("displayMessage", "Message Deleted");
                        disp = sc.getRequestDispatcher("/jsp/view.jsp");
                    }
                    // If the user elected to delete homework, then delete it.
                    else if (FormFields.DELHOMEWORK.equals(link)) {
                        int hwnum = (new Integer(param)).intValue();
                        HomeworkContainer hc =
                            ((HomeworkContainer[]) st.getValue("homeworkContainer"))[hwnum];
                        SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).moveHomeworkToDeleted(hc);
                        st.putValue("displayMessage", "Homework Deleted");
                        disp = sc.getRequestDispatcher("/jsp/view.jsp");
                    }
                    // If the user elected to reply to a mail, then display the mail form.
                    // The jsp will take care of pre-populating the fields.
                    else if (FormFields.REPLY.equals(link)) {
                        st.putValue(FormFields.MAILNUM, input.getParameter(FormFields.MAILNUM));
                        disp = sc.getRequestDispatcher("/jsp/TeacherMailForm.jsp");
                    }
                    // If the user elected to view a homework, then display it.
                    else if (FormFields.HWLINK.equals(link)) {
                        int hwnum = (new Integer(param).intValue());
                        HomeworkContainer homeworkC[] =
                            (HomeworkContainer[]) st.getValue("homeworkContainer");
                        st.putValue(FormFields.HWNUM, param);

                        disp =
                            sc.getRequestDispatcher("/jsp/TeacherHomeworkForm.jsp");
                    }
                    // If the user elected to grade homework, then populate the grades
                    // associated with the homework and display them.
                    else if (FormFields.GRADELINK.equals(link)) {
                        int loc =
                            new Integer(st.getValue(FormFields.CLASSNUM).toString()).intValue();
                        String classid =
                            ((ClassContainer[]) st.getValue("classContainer"))[loc].getClassAssignedID().toString();
                        UserContainer sic[] =
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadStudentsInClass(
                                new StringItem(SchoolDBSQL.CLASSASSIGNEDID, classid, false));
                        GradeContainer gc[] = new GradeContainer[sic.length];
                        SubmissionContainer subC[] = new SubmissionContainer[sic.length];
                        String homeworkid =
                            (String) input.getParameter(SchoolDBSQL.HWASSIGNEDID);
                        for (int i = 0; i < sic.length; i++) {
                            gc[i] =
                                GradeContainer.getGradeContainer(classid, homeworkid, sic[i].getAssignedID().toString(), st.getValue(FormFields.SCHOOLNAME).toString());
                            subC[i] =
                                SubmissionContainer.getSubmissionContainer(classid, homeworkid, sic[i].getAssignedID().toString(), st.getValue(FormFields.SCHOOLNAME).toString());
                        }

                        st.putValue("studentsInClass", sic);
                        st.putValue("grades", gc);
                        st.putValue("submissions", subC);
                        st.putValue(FormFields.HWNUM, param);
                        disp =
                            sc.getRequestDispatcher("/jsp/ClassHomeworkGrades.jsp");
                    }
                    // If the user elected to save grades, parse the list of grades and save them.
                    else if ("Save Grade".equals(link)) {
                        GradeContainer gc[] =
                            (GradeContainer[]) st.getValue("grades");
                        SubmissionContainer submissions[] = new SubmissionContainer[gc.length];
                        for (int i = 0; i < gc.length; i++) {
                            gc[i].getGrade().setValue((String) input.getParameter(SchoolDBSQL.GRADESCORE + gc[i].getStudentID().toString()));
                            gc[i].getComment().setValue((String) input.getParameter(SchoolDBSQL.GRADECOMMENT + gc[i].getStudentID().toString()));
                            submissions[i] = SubmissionContainer.getSubmissionContainer(gc[i].getClassID().toString(),
                                                                                        gc[i].getHomeworkID().toString(),
                                                                                        gc[i].getStudentID().toString(),
                                                                                        (String) st.getValue(FormFields.SCHOOLNAME));
                            submissions[i].getUpdateAllowed().setValue((String) input.getParameter(SchoolDBSQL.SUBMISSIONUPDATEALLOWED + gc[i].getStudentID().toString()));
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(submissions[i]);
//                          gc[i].setGrade(new StringItem(SchoolDBSQL.GRADESCORE,
//                                  (String) input.getParameter(SchoolDBSQL.HWASSIGNEDID + gc[i].getStudentID().toString()), true));
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(gc[i]);
                        }
                        st.putValue("displayMessage", "Grades saved");
                        disp = sc.getRequestDispatcher("/jsp/view.jsp");
                    }
                    // If the user elected to change his or her password, then display
                    // the password form.
                    else if (FormFields.CHANGEPASSWORD.equals(link)) {
                        disp = sc.getRequestDispatcher("/jsp/PasswordForm.jsp");
                    }
                    else if (FormFields.PROFILELISTLINK.equals(link)) {
                        int loc =
                            new Integer(st.getValue(FormFields.CLASSNUM).toString()).intValue();
                        String classid =
                            ((ClassContainer[]) st.getValue("classContainer"))[loc].getClassAssignedID().toString();
                        UserContainer sic[] =
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadStudentsInClass(
                                new StringItem(SchoolDBSQL.CLASSASSIGNEDID, classid, false));
                        st.putValue("studentsInClass", sic);
                        disp = sc.getRequestDispatcher("/jsp/StudentProfileList.jsp");
                    }
                    else if (FormFields.PROGRESSLISTLINK.equals(link)) {
                        int loc =
                            new Integer(st.getValue(FormFields.CLASSNUM).toString()).intValue();
                        String classid =
                            ((ClassContainer[]) st.getValue("classContainer"))[loc].getClassAssignedID().toString();
                        UserContainer sic[] =
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadStudentsInClass(
                                new StringItem(SchoolDBSQL.CLASSASSIGNEDID, classid, false));
                        st.putValue("studentsInClass", sic);
                        disp = sc.getRequestDispatcher("/jsp/ProgressReportList.jsp");
                    }
                    else if (FormFields.ATTENDANCEEDIT.equals(link)) {
                        int loc =
                            new Integer(st.getValue(FormFields.CLASSNUM).toString()).intValue();
                        String classid =
                            ((ClassContainer[]) st.getValue("classContainer"))[loc].getClassAssignedID().toString();
                        UserContainer sic[] =
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadStudentsInClass(
                                new StringItem(SchoolDBSQL.CLASSASSIGNEDID, classid, false));
                        String dateString = (String) input.getParameter(FormFields.ATTENDANCEDATE);
							st.putValue(FormFields.ATTENDANCEDATE, dateString);

                        st.putValue("studentsInClass", sic);
                        disp = sc.getRequestDispatcher("/jsp/attendanceentry.jsp");
                    }
                    else if (FormFields.ATTENDANCESUMMARY.equals(link)) {
                        int loc =
                            new Integer(st.getValue(FormFields.CLASSNUM).toString()).intValue();
                        String classid =
                            ((ClassContainer[]) st.getValue("classContainer"))[loc].getClassAssignedID().toString();
                        UserContainer sic[] =
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadStudentsInClass(
                                new StringItem(SchoolDBSQL.CLASSASSIGNEDID, classid, false));
                        String dateString = (String) input.getParameter(FormFields.ATTENDANCEDATE);
                        st.putValue(FormFields.ATTENDANCEDATE, dateString);

                        st.putValue("studentsInClass", sic);
                        disp = sc.getRequestDispatcher("/jsp/attendancesummary.jsp");
                    }
                    // If the user elected to save attendance, parse the list of attendances and save them.
                    else if ("Save Attendance".equals(link)) {
    int loc =
        new Integer(st.getValue(FormFields.CLASSNUM).toString()).intValue();

	String dateString = input.getParameter(FormFields.ATTENDANCEDATE);

	GregorianCalendar date = new GregorianCalendar();
    if (dateString != null && !"".equals(dateString)) {
		try {
	        date.setTime(Types.sdfMMDDYYYY.parse(dateString));
		}
		catch (java.text.ParseException pe) {
			//SchoolLogger.logger.log(Level.SEVERE, "The date to save could not be parsed");
		}
    }
    else {
		// something not right happened
		//SchoolLogger.logger.log(Level.SEVERE, "An empty dateString came through for saving dates");
		return;
	}

    String classid =
        ((ClassContainer[]) st.getValue("classContainer"))[loc].getClassAssignedID().toString();
    UserContainer sic[] =
        SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadStudentsInClass(
            new StringItem(SchoolDBSQL.CLASSASSIGNEDID, classid, false));
    for (int i = 0; i < sic.length; i++) {

		// TODO: Get changed flag variable
		// If changed, do the following
		AttendanceContainer ac =
			AttendanceContainer.getAttendanceContainer(sic[i].getAssignedID().toString(), classid, Types.sdfMMDDYYYYslash.format(date.getTime()).toString(), (String) st.getValue(FormFields.SCHOOLNAME));
			ac.getType().setValue((String) input.getParameter(SchoolDBSQL.USRASSIGNEDID + sic[i].getAssignedID().toString() + SchoolDBSQL.ATNDDATE + Types.sdfMMDDYYYY.format(date.getTime()).toString()));
			if (!(ac.getType().toString().trim().length()==0)) {
				//SchoolLogger.logger.log(Level.INFO, "Saved attendance");
				SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(ac);
			}
			// else delete the tardy/absence from the table
			else {
				SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).deleteAttendance(ac.getStudentID(), ac.getClassID(), ac.getDate());
			}

    }

                        st.putValue("displayMessage", "Attendance saved");
//                        disp = sc.getRequestDispatcher("/jsp/view.jsp");
                        disp = sc.getRequestDispatcher("/jsp/attendancesummary.jsp");
                    }
                    else if (FormFields.PROGRESSLINK.equals(link)) {
                        int classnum =
                            (new Integer((String) st.getValue(FormFields.CLASSNUM))).intValue();
                        ClassContainer classContainer[] =
                            (ClassContainer[]) st.getValue("classContainer");
                        String teacherID = SchoolDBSQL.getSchoolDBSQL(schoolName)
                                                .getClassTeacherID(
                                                    classContainer[classnum].getClassAssignedID()).toString();

                        String studentID = param;//"82";
                        //String studentID = input.getParameter("SELECTEDSTUDENT");
                        UserContainer teacherContainer = UserContainer.getUserContainer(teacherID, schoolName);
                        HomeworkContainer homeworkContainer[] = SchoolDBSQL.getSchoolDBSQL(schoolName).loadTeacherClassHomework(classContainer[classnum].getClassAssignedID());
                        GradeContainer gradeContainer[] = new GradeContainer[homeworkContainer.length];

                        for (int j = 0; j < homeworkContainer.length; j++) {
                            gradeContainer[j] =
                                GradeContainer.getGradeContainer(
                                    homeworkContainer[j].getClassID().toString(),
                                    homeworkContainer[j].getHomeworkID().toString(),
                                    studentID,
                                    schoolName);
                        }

                        st.putValue("teacherContainer", teacherContainer);
                        st.putValue("homeworkContainer", homeworkContainer);
                        st.putValue("studentGrade", gradeContainer);
                        st.putValue("studentProgress", UserContainer.getUserContainer(studentID, schoolName));
                        disp = sc.getRequestDispatcher("/jsp/ProgressReport.jsp");

                    }
                    else if (FormFields.STUDENTPROFILE.equals(link)) {
                        String studentID = param;
                        loadViewStudentInfo(st, param, schoolName);
//                      loadViewStudentInfo(infoToken, param, infoToken.getValue(FormFields.SCHOOLNAME).toString());
                        disp = sc.getRequestDispatcher("/jsp/StudentProfile.jsp");
                    }
                    // If the user elected to save a password change, then validate
                    // the change request and change it or display an error as appropriate.
                    else if ("Change Password".equals(link)) {
                        // if current password is valid, then
                        UserContainer tc =
                            (UserContainer) st.getValue("teacherContainer");
                        String oldPIParam =
                            input.getParameter(FormFields.CURRENTPASSWORD);
                        PasswordItem oldPI =
                            new PasswordItem(SchoolDBSQL.USRPASSWORD, oldPIParam, true);
                        PasswordItem newPI =
                            new PasswordItem(SchoolDBSQL.USRPASSWORD, (String) null, true);
                        FormParser.getNewPassword(input, newPI);
                        if (SecurityAuthorizer.isValidLogin(tc.getAssignedID().toString(), oldPIParam, st.getValue(FormFields.SCHOOLNAME).toString())) {
                            if (newPI.getObject() == null) {
                                st.putValue(
                                    "displayMessage",
                                    "The first new password you entered did not match the second. Your password has not been changed.");
//                          disp = sc.getRequestDispatcher("/TeacherClassInfo.jsp");
//                            disp = sc.getRequestDispatcher("/view.jsp");
                            disp = sc.getRequestDispatcher("/jsp/PasswordForm.jsp");
                            }
                            else {
                                SchoolDBSQL.getSchoolDBSQL(
                                    (String) st.getValue(FormFields.SCHOOLNAME)).changeUserPassword(tc.getAssignedID(), oldPI, newPI);
                                st.putValue(
                                    "displayMessage",
                                    "Password changed");
//                              disp = sc.getRequestDispatcher("/view.jsp");
//                              disp = sc.getRequestDispatcher("/PasswordForm.jsp");
                                if ("TRUE".equalsIgnoreCase(input.getParameter(FormFields.PSWDCHGREQ))) {
                                    tc.getPasswordChangeRequired().setValue("FALSE");
                                    disp = sc.getRequestDispatcher("/jsp/TeacherClassInfo.jsp");
                                }
                                else {
                                    disp = sc.getRequestDispatcher("/jsp/view.jsp");
                                }
                            }
                        }
                        else {
                            st.putValue("displayMessage", "Password incorrect");
//                          disp = sc.getRequestDispatcher("/view.jsp");
                            disp = sc.getRequestDispatcher("/jsp/PasswordForm.jsp");
                        }
                    }
                    // If the user elected to send an email, send it
                    else if ("Send".equals(link)) {
// TODO make sure this always needs to be a new container
                        MessageContainer mc = MessageContainer.getMessageContainer("-1", st.getValue(FormFields.SCHOOLNAME).toString());
                        FormParser.updateMessage(input, mc);
                        SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(mc);
                        ContactContainer cc[] =
                            FormParser.createContacts(input, mc, st.getValue(FormFields.SCHOOLNAME).toString());
                        for (int i = 0; i < cc.length; i++) {
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(cc[i]);
                        }
                        st.putValue("displayMessage", "Message Sent");
                        disp = sc.getRequestDispatcher("/jsp/view.jsp");
                    }
                    // If the user elected to cancel sending an email or homework, then
                    // return to the main page.
                    else if ("Cancel".equals(link)) {
                        current = input.getParameter(FormFields.CURRENT);
                        disp = sc.getRequestDispatcher("/jsp/view.jsp");
                    }
                    // If the user elected to assign a homework, save the homework
                    else if ("Assign".equals(link) || "Save".equals(link)) {
// TODO the following needs to do a 'getHomeworkContainer' using a real ID and dynamic
//                      HomeworkContainer hc = HomeworkContainer.getHomeworkContainer("-1", SchoolDBSQL.DEVDATABASENAME);
                        HomeworkContainer hc = FormParser.updateHomework(input, st.getValue(FormFields.SCHOOLNAME).toString());

                        // save homework before parsing attachment so we can get
                        // the unique hw id to use as the save folder if there are any attachments
                        if ("-1".equals(hc.getHomeworkID().toString())) {
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(hc);
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadHomework(hc);
                        }

                        String deleteAttachments[] =
                            FormParser.parseList((String) input.getParameter(FormFields.DELATTACHMENT));
                        AttachmentContainer removedContainer;
                        for (int i = 0; i < deleteAttachments.length; i++) {
                            removedContainer =
                                hc.removeAttachment(deleteAttachments[i]);
                            if (removedContainer != null) {
                                SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).deleteHWAttachment(
                                    removedContainer.getAssignedAttachmentID());
                                // delete file
                            }
                        }
                        String displayMessage = "";
                        if (!"".equals(input.getParameter(SchoolDBSQL.ATTFILENAME))) {// + ".filename"))) {
//                          FormParser.updateAttachment(input, hc, ((String) st.getValue(FormFields.SCHOOLNAME)) + "\\" + FormFields.HOMEWORKATTACHMENT, st.getValue(FormFields.SCHOOLNAME).toString());
//                            FormParser.updateAttachment(input, hc, ((String) st.getValue(FormFields.SCHOOLNAME)) + "/" + FormFields.HOMEWORKATTACHMENT, st.getValue(FormFields.SCHOOLNAME).toString());
                            try {
                                //SchoolLogger.logger.log(Level.INFO, "Attachment");
                                FormParser.updateAttachment(input, hc, ((String) st.getValue(FormFields.SCHOOLNAME)) + ConfigurationItems.PATHSEPARATOR + FormFields.HOMEWORKATTACHMENT, st.getValue(FormFields.SCHOOLNAME).toString());
                            }
                            catch (IOException ioe) {
                                displayMessage = "Unable to save attachment(s). Please try again later. ";
                            }
                            // save the homework again to save the attachments and associations in the
                            // tables
                            SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(hc);
                        }

                        displayMessage = displayMessage + "Homework saved.";
                        st.putValue("displayMessage", displayMessage);
//                      disp = sc.getRequestDispatcher("/TeacherClassInfo.jsp");
disp = sc.getRequestDispatcher("/jsp/view.jsp");
                    }
                    // Unknown link was clicked - default to the login page
                    else {
                        //SchoolLogger.logger.log(Level.INFO, "linkclicked was not recognized");
                        //SchoolLogger.logger.log(Level.INFO, "link: " + link);
                        disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
                    }
                }
                // Default to the login page
                else {
                    disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
                }
            }
            // If the user elected to log out,then dispose of the token and display the
            // teacher login page
            else if (FormFields.LOGOUT.equals(link)) {
                //SchoolLogger.logger.log(Level.INFO, "Logged out 2");
                if (st != null) {
                    SecurityAuthorizer.removeToken(st.toString());
                }
                input.setAttribute("message", "User logged out.");
                disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
            }
            else {
                //SchoolLogger.logger.log(Level.INFO, "show login again");
                input.setAttribute(
                    "message",
                    "Your login has expired. Please log in again");
                    Enumeration attrList = input.getParameterNames();
                    String attrName;
                    while (attrList.hasMoreElements()) {
                        attrName = (String) attrList.nextElement();
                        input.setAttribute(attrName, input.getParameter(attrName));
                    }
                disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
            }
        }
        // If the token was invalid or did not exist, try logging in user
        // via username/password.
        else if (
            input.getParameter(SchoolDBSQL.USRSCHOOLID) != null
                && input.getParameter(SchoolDBSQL.USRPASSWORD) != null) {
            if (SecurityAuthorizer.isValidTeacherLogin(
                    input.getParameter(SchoolDBSQL.USRSCHOOLID),
                    input.getParameter(SchoolDBSQL.USRPASSWORD),
                    schoolName)) {
                //SchoolLogger.logger.log(Level.INFO, "valid login");
                st = SecurityAuthorizer.generateToken();
                st.putValue(FormFields.USRTYPE, new Character('T'));
                // put the Token in the request so the jsp can retrieve it
                input.setAttribute(FormFields.SESSION, st);

                st.putValue(FormFields.TOKEN, st.toString());

                // Add school name here
                // TODO get the school name from the input
                st.putValue(FormFields.SCHOOLNAME, schoolName);

                UserContainer teacherContainer =
                    UserContainer.getUserContainer(SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).getAssignedID
                        (input.getParameter(SchoolDBSQL.USRSCHOOLID), SchoolDBSQL.TEACHER), st.getValue(FormFields.SCHOOLNAME).toString());

                teacherContainer.getFailures().setValue("0");

                SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).save(
                    teacherContainer);

                st.putValue("teacherContainer", teacherContainer);

                // Get classes and teacher info
                // The two arrays are synchronized so that the ith entry in one corresponds to
                // the ith entry in the other
                // This is inefficient, since we probaby are storing (and querying) the same sender's
                // information more than once
                ClassContainer teacherClasses[] =
                    SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).loadTeacherClasses(teacherContainer.getAssignedID());
                UserContainer teacherClassStudents[] =
                    new UserContainer[teacherClasses.length];

                st.putValue("classContainer", teacherClasses);
                st.putValue("teacherClassStudent", teacherClassStudents);

                // Get communications and sender (teacher) info
                // The two arrays are synchronized so that the ith entry in one corresponds to
                // the ith entry in the other
                // This is inefficient, since we may be storing (and querying) the same sender's
                // information many times
//                if (teacherClasses.length != 0) {
                    getTodaysPage(teacherContainer, st);
//                  getClassPage(teacherClasses[0], teacherContainer, st);
//                }
                // Reset the last date/time login and reset the failed login attempts
                SchoolDBSQL.getSchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME)).resetUser(teacherContainer.getAssignedID());

                // Default the class number to the first one in the array of classes
                if (teacherClasses.length == 0) {
                    st.putValue(FormFields.CLASSNUM, "-1");
                }
                else {
                    st.putValue(FormFields.CLASSNUM, "-2");
//                  st.putValue(FormFields.CLASSNUM, "0");
                }
                if (teacherContainer.getPasswordChangeRequired().toString().equalsIgnoreCase("TRUE")) {
                    st.putValue(
                        "displayMessage",
                        "A password change is required for your user ID.");
                    disp = sc.getRequestDispatcher("/jsp/PasswordForm.jsp");
                }
                else {
                    disp = sc.getRequestDispatcher("/jsp/TeacherClassInfo.jsp");
                }
            }
            // Could not validate the user's username/password
            else {
                //SchoolLogger.logger.log(Level.WARNING, "Invalid username/password");
                input.setAttribute(
                    "message",
                    "The username/password you entered could not be validated.");
                disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
            }
        }
        // Default to the main teacher page
        else {
            //SchoolLogger.logger.log(Level.INFO, "First login attempt");
            input.setAttribute("message", null);
            disp = sc.getRequestDispatcher("/jsp/TeacherLogin.jsp");
        }

        disp.include(input, response);
    }

    /**
     * Forwards all calls to doPost
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     **/
    public void doGet(HttpServletRequest input, HttpServletResponse response)
        throws ServletException, IOException {

            //SchoolLogger.logger.log(Level.INFO, "//////////////////////////////////////////////////////////////");
            doPost(input, response);

    }

    /**
     * Loads all mail and homework for a class.
     * @param cc The class for which information is to be loaded.
     * @param tc The user container for which information is to be loaded.
     * @param st The token where information is to be stored.
     */
    public void getClassPage(ClassContainer cc, UserContainer tc, SecurityToken st) {
        // Get homework
        // The array is in the same order as the class array, so the ith entry in one
        // corresponds to the ith entry in the other
        // This could potentially contain a lot of information. Should the architecture
        // be changed so that homework is looked up as needed?
        //      SchoolDBSQL db = new SchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME));
        HomeworkContainer teacherHomework[] =
            SchoolDBSQL.getSchoolDBSQL(
                (String) st.getValue(FormFields.SCHOOLNAME)).loadTeacherClassHomework(
                cc.getClassAssignedID());

        st.putValue("homeworkContainer", teacherHomework);

        // Get communications and sender (teacher) info
        // The two arrays are synchronized so that the ith entry in one corresponds to
        // the ith entry in the other
        // This is inefficient, since we may be storing (and querying) the same sender's
        // information many times
        ContactContainer teacherCommunications[] =
            SchoolDBSQL.getSchoolDBSQL(
                (String) st.getValue(FormFields.SCHOOLNAME)).loadContacts(
                tc.getAssignedID().toString(),
                cc.getClassAssignedID().toString());
        UserContainer studentWhoSentMail[] =
            new UserContainer[teacherCommunications.length];
        for (int i = 0; i < teacherCommunications.length; i++) {
            studentWhoSentMail[i] =
                UserContainer.getUserContainer(
                    teacherCommunications[i].getFromID().toString(), st.getValue(FormFields.SCHOOLNAME).toString());
        }
        st.putValue("communicationContainer", teacherCommunications);
        st.putValue("studentWhoSentMail", studentWhoSentMail);

    }
    /**
     * Loads all mail and homework for a class.
     * @param cc The class for which information is to be loaded.
     * @param tc The user container for which information is to be loaded.
     * @param st The token where information is to be stored.
     */
    public void getTodaysPage(UserContainer tc, SecurityToken st) {
        // Get homework
        // The array is in the same order as the class array, so the ith entry in one
        // corresponds to the ith entry in the other
        // This could potentially contain a lot of information. Should the architecture
        // be changed so that homework is looked up as needed?
        //      SchoolDBSQL db = new SchoolDBSQL((String) st.getValue(FormFields.SCHOOLNAME));
        HomeworkContainer teacherHomework[] =
            SchoolDBSQL.getSchoolDBSQL(
                (String) st.getValue(FormFields.SCHOOLNAME)).loadTodaysTeacherHomework(
                tc.getAssignedID());

        st.putValue("homeworkContainer", teacherHomework);

        // Get communications and sender (teacher) info
        // The two arrays are synchronized so that the ith entry in one corresponds to
        // the ith entry in the other
        // This is inefficient, since we may be storing (and querying) the same sender's
        // information many times
        ContactContainer teacherCommunications[] =
            SchoolDBSQL.getSchoolDBSQL(
                (String) st.getValue(FormFields.SCHOOLNAME)).loadTodaysContacts(
                tc.getAssignedID().toString());
        UserContainer studentWhoSentMail[] =
            new UserContainer[teacherCommunications.length];
        for (int i = 0; i < teacherCommunications.length; i++) {
            studentWhoSentMail[i] =
                UserContainer.getUserContainer(
                    teacherCommunications[i].getFromID().toString(), st.getValue(FormFields.SCHOOLNAME).toString());
        }
        st.putValue("communicationContainer", teacherCommunications);
        st.putValue("studentWhoSentMail", studentWhoSentMail);

    }
    // The following is a duplicate of the method in EditorCMD
    /**
     * Loads a student, along with classes, teachers, and parents, into the token.
     * @param infoToken The token where the information is to be stored.
     * @param id The assigned ID of the student to load.
     */
    private void loadViewStudentInfo(SecurityToken infoToken, String id, String dbName) {
        infoToken.putValue(FormFields.EDITSTATUS, FormFields.VIEW);
        // infoToken.putValue(FormFields.CLICKSTATUS, FormFields.DISABLED);
        Item[][] assignedClassList;
        Item[][][] assignedTeacherList;
        infoToken.putValue(
            "studentContainer",
            PairedUserContainer.getPairedContainer(id, dbName));
        assignedClassList =
            SchoolDBSQL
                .getSchoolDBSQL(infoToken.getValue(FormFields.SCHOOLNAME).toString())
                .loadStudentAssignedClassList(
                    new StringItem(
                        SchoolDBSQL.USRASSIGNEDID,
                        id,
                        true));
        assignedTeacherList = new Item[assignedClassList.length][][];
        for (int i = 0; i < assignedClassList.length; i++) {
            assignedTeacherList[i] = SchoolDBSQL.getSchoolDBSQL(dbName).loadTeacherFromClassID(assignedClassList[i][0]);
        }
        infoToken.putValue("assignedClassList", assignedClassList);
        infoToken.putValue("assignedTeacherList", assignedTeacherList);
        infoToken.putValue("assignedParentList", SchoolDBSQL.getSchoolDBSQL(dbName).loadChildrensParents(id));
        infoToken.putValue("availableParentList",
            SchoolDBSQL.getSchoolDBSQL(dbName).loadAvailableParents());
    }

}

